import React from 'react';
import { observer } from 'mobx-react';
import { observable, action, toJS } from 'mobx';
import { WeaFormItem, WeaTable, WeaTools, WeaDialog, WeaSearchGroup, WeaTableEdit, WeaTableEditable, WeaLocaleProvider } from 'ecCom';
import { Button, Icon } from "antd";
import { WeaForm, WeaSwitch } from 'comsMobx';
import SettingStore from './SettingsStore';
const getLabel = WeaLocaleProvider.getLabel;
@observer
class Setting extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {},
            store: new SettingStore(),
        };
        // 将当前组件实例传递到元素组件，以便元素组件获取到该组件
        props.getInstance && props.getInstance(this);
        this.onSave = this.onSave.bind(this);
    }

    componentWillMount() {
        const { params = {} } = this.props;
        const { eid } = params;
        const { doInit } = this.state.store
        doInit(this, eid);
    }

    render() {
        const { store } = this.state;
        const { setOperationtype, form, dataSource, columns, buttons, visible, onTableCheckSelect, selectedRowKeys, dialogTitle, setVisible, onDeleteClick, getElementSettingForm } = store;
        const rowSelection = {
            onChange(selectedRowKeys, selectedRows) {
                onTableCheckSelect(selectedRowKeys, selectedRows)
            },
        };
        const customComponent = <div style={{ margin: "10px 50px 10px auto" }}>
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6emwi0`}
                type="primary"
                size="small"
                onClick={() => { getElementSettingForm({ operation: "add" }); setOperationtype("addSetting") }}
                className='crm_enterprise_elemetn_but'
            >
                <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@7tcixy`} type="plus" />
            </Button>
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@m5y6w3`}
                type="primary"
                disabled={!`${selectedRowKeys}`}
                size="small"
                onClick={() => { onDeleteClick() }}
                className='crm_enterprise_elemetn_but'
            >
                <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@5e0t48`} type="minus" />
            </Button>
        </div>
        // console.log(buttons)
        return (
            <div className="portal-demo-element-setting">
                {/* <WeaSearchGroup title="内容来源" items={[]} customComponent={customComponent} showGroup={true}> */}
                {customComponent}
                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@woy9ul`}
                    columns={columns}
                    dataSource={dataSource}
                    draggable={true}
                    // onDrop={this.drop}
                    rowSelection={rowSelection}
                />
                {/* </WeaSearchGroup> */}
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@42wp3s`}
                    title={dialogTitle}
                    visible={visible}
                    buttons={toJS(buttons)}
                    onCancel={() => setVisible(false)}
                    style={{ width: 900, height: 600 }}
                >
                    
                    {this.dialogBody()}
                </WeaDialog>
            </div>
        );
    }

    onSave() {
        // 保存元素设置数据
        // 如果有必填项，校验不通过时，需要return false;
        const { data } = this.state;
        WeaTools.callApi('/api/mainportal/element/demo/saveSettingData', 'POST', { ...data });
    }

    dialogBody() {
        const { form, formitem, operationtype, formfiled = [], editbatledatas = [], paramsdatas = [] } = this.state.store;
        if (operationtype == "paramsSetting") {
            const columns = [
                {
                    title: getLabel('561', '参数'),
                    dataIndex: 'param',
                    width: "50%",
                    com: [
                        {
                            key: 'param',
                            type: "select",
                            viewAttr: 3,
                            options: paramsdatas
                        },
                    ],
                },
                {
                    title: getLabel('33234', '类型'),
                    dataIndex: "cascader",
                    width: "50%",
                    com: [
                        {
                            type: "CASCADER",
                            key: "cascader",
                            viewAttr: 3,
                            compDef: {
                                type: "select",
                                options: [
                                    {
                                        key: "1",
                                        selected: true,
                                        showname: getLabel('453', '固定值'),
                                    },
                                    {
                                        key: "2",
                                        selected: false,
                                        showname: getLabel('21740', '表单字段'),
                                    },
                                ],
                                subChildren: {
                                    1: {
                                        type: 'input',
                                        style: { width: 160 },
                                    },
                                    2: {
                                        type: "select",
                                        otherParams: { showSearch: true, optionFilterProp: "children" },
                                        options: toJS(formfiled),
                                    }
                                }
                            }
                        }
                    ]
                },
            ];
            const validator = {
                rules: {
                    param: "required",
                    cascader: "required1",
                    // defaultvalue: "required",
                },
                errorMessage: {
                    required: getLabel('385869', '此项必填'),
                    required1: getLabel('385869', '此项必填'),
                },
                customRegister: [
                    {
                        name: "required1",
                        rules: (value) => {
                            let key = true;
                            value.map(item => {
                                if (item == "") {
                                    key = false;
                                }
                            })
                            // console.log(key)
                            return key;
                        },
                        errorMessage: getLabel('385869', '此项必填')
                    }
                ]
            };
            return (
                <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@cz7mva`}
                    columns={columns}
                    datas={toJS(editbatledatas)}
                    showCopy={false}
                    ref={el => { this.tableEdit = el }}
                    validator={validator}
                />
            )
        } else {
            const { isFormInit } = form;
            let group = [];
            isFormInit && toJS(formitem).map((c, index) => {
                let items = [];
                c.items.map((field, index) => {
                    let col = 1;
                    if (field.conditionType.toUpperCase() == WeaTools.types.CASCADER) col = 1;
                    items.push({
                        com: (
                            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@syt17j@${field.domkey[0]}`}
                                label={`${field.label}`}
                                labelCol={{ span: `${field.labelcol}` }}
                                ratio1to2
                                error={form.getError(field)}
                                tipPosition="bottom"
                                wrapperCol={{ span: `${field.fieldcol}` }}>
                                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@u477gm@${field.domkey[0]}`} fieldConfig={field} form={form} />
                            </WeaFormItem>),
                        col: col,
                        hide: form.isHide(field, (keys, allParams) => {
                            return false;
                        })
                    })
                });
                group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@0yutz1@${index}`} needTigger={false} showGroup={c.defaultshow} items={items} />)
            });
            return group;
        }
    }
    getRowSelection = rowSelection => {
        return null;
    };
}

export default Setting;
